<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警告导航 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
      <!-- 选择商品分类 -->
      <el-row style="margin-top:20px;">
        <el-col>
          选择商品分类：
          <el-cascader
            expand-trigger="hover"
            v-model="selectdKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加参数</el-button>
          <!-- 动态属性表格 -->
          <el-table :data="manyTableDate" border stripe style="margin-top:15px;">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>

                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加动态静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableDate" border stripe style="margin-top:15px;">
            <!-- 展开行 -->
            <el-table-column type="expand"></el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数 对话框 -->
    <el-dialog
      :title="'提示' + titleText"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addDialogClosed"
    >
      <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'提示' + titleText"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="editDialogClosed"
    >
      <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //获取商品分类列表
      cateList: [],
      //级联选择框的配置对象
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //级联选择框双向绑定的数据
      selectdKeys: [],
      //被激活的页签的名称
      activeName: "many",
      //动态参数数据
      manyTableDate: [],
      //静态参数数据
      onlyTableDate: [],
      //控制添加参数对话框是否显示
      addDialogVisible: false,
      //添加数据的表单对象
      addFrom: {},
      //添加数据 表单校验规则
      addFromRules: {
        attr_name: [
          { required: true, message: "请输入用户名称", trigger: "blur" }
        ]
      },
      //控制修改对话框的显示与隐藏
      editDialogVisible: false,
      //修改的表单数据对象
      editFrom: {},
      //修改数据 表单校验规则
      editFromRules: {
        attr_name: [
          { required: true, message: "请输入用户名称", trigger: "blur" }
        ]
      },
      //控制按钮 与文本框的切换显示
      inputVisible: false,
      //文本框中输入的内容
      inputValue: ""
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取数据失败！");
      }
      this.cateList = res.data;
    },
    //级联选择框选中 触发事件
    handleChange() {
      this.getParamsData();
    },
    //tab页签被激活事件
    handleClick() {
      this.getParamsData();
    },
    //获取参数列表数据
    async getParamsData() {
      if (this.selectdKeys.length !== 3) {
        this.selectdKeys = [];
        this.manyTableDate = []
        this.onlyTableDate = []
        return;
      }
      //更具所选数据的 di 和当前所处的面板 获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败！");
      }

      res.data.forEach(item => {
        if (item.attr_vals === "") {
          item.attr_vals = [];
        } else {
          item.attr_vals = item.attr_vals.split(" ");
        }
        //添加属性 控制文本框的控制隐藏
        item.inputVisible = false;
        //添加属性 文本框输入的值
        item.inputValue = "";
      });
      console.log(res);
      if (this.activeName === "many") {
        this.manyTableDate = res.data;
      } else {
        this.onlyTableDate = res.data;
      }
    },
    //监听对话框关闭事件
    addDialogClosed() {
      this.$refs.addFromRef.resetFields();
    },
    //添加事件
    addParams() {
      this.$refs.addFromRef.validate(async valid => {
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addFrom.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加失败！");
        }
        this.$message.success("添加成功！");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    //点击按钮展示 修改对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("请求失败！");
      }
      this.editFrom = res.data;
      this.editDialogVisible = true;
    },
    //监听对话框关闭事件
    editDialogClosed() {
      this.$refs.editFromRef.resetFields();
    },
    //点击按钮修改参数信息
    editParams() {
      this.$refs.editFromRef.validate(async valid => {
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editFrom.attr_id}`,
          {
            attr_name: this.editFrom.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改参数失败！");
        }
        this.$message.success("修改成功！");
        this.editDialogVisible = false;
        this.getParamsData();
      });
    },
    //更具id 删除对应的数据
    removeParams(attr_id) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${attr_id}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败！");
          }
          this.getParamsData();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //文本框失去焦点 或 按下了enter 都会触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      //没有return 则输入了内容
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      //需要发起请求保存操作
      this.saveAttrVals(row)
    },
    //点击按钮 展示文本输入框
    showInput(row) {
      row.inputVisible = true;
      //让文本框自动获取焦点
      //$nextTic 就是当页面上元素被重新渲染的时候执行
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //删除对应的tag
    handleClose(i, row) {
      row.attr_vals.splice(i,1)
      this.saveAttrVals(row)
      
    },
    //将对attr_vals删除操作保存到数据库
    async saveAttrVals(row) {
       //需要发起请求保存操作
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改参数失败！");
      }
      this.$message.success("修改参数成功！");
    }
  },
  computed: {
    //如果没有选中三级 则返回true 否则返回false
    isBtnDisabled() {
      if (this.selectdKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    //选中当前三级的id
    cateId() {
      if (this.selectdKeys.length === 3) {
        return this.selectdKeys[2];
      }
      return null;
    },
    //动态计算添加参数标题
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态参数";
      }
    }
  }
};
</script>

<style lang="less" scoped>
.el-form {
  .el-input {
    width: 85%;
    margin-left: 15px;
  }
}
.input-new-tag {
  width: 100px;
}
.el-tag {
  margin-right: 15px;
}
</style>